import { useState, useCallback } from 'react';
import { message } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs, { Dayjs } from 'dayjs';

const MAX_DATE_RANGE = 90; // 最大日期范围（天）

export interface UseDateRangeOptions {
  defaultRange?: [Dayjs, Dayjs];
  maxRange?: number;
}

export interface UseDateRangeResult {
  dateRange: [Dayjs, Dayjs];
  setDateRange: RangePickerProps['onChange'];
  disabledDate: (current: Dayjs) => boolean;
  ranges: Record<string, [Dayjs, Dayjs]>;
}

type RangeValue = Parameters<Required<RangePickerProps>['onChange']>[0];

export const useDateRange = (options: UseDateRangeOptions = {}): UseDateRangeResult => {
  const {
    defaultRange = [dayjs().subtract(6, 'day'), dayjs()],
    maxRange = MAX_DATE_RANGE,
  } = options;

  const [dateRange, setDateRangeState] = useState<[Dayjs, Dayjs]>(defaultRange);

  const disabledDate = useCallback(
    (current: Dayjs) => {
      // 禁用未来日期
      if (current.isAfter(dayjs(), 'day')) {
        return true;
      }

      // 如果已选择开始日期，检查结束日期选择范围
      if (dateRange[0] && !dateRange[1]) {
        return (
          current.isBefore(dateRange[0], 'day') ||
          current.isAfter(dateRange[0].add(maxRange, 'day'), 'day')
        );
      }

      // 如果已选择结束日期，检查开始日期选择范围
      if (!dateRange[0] && dateRange[1]) {
        return (
          current.isAfter(dateRange[1], 'day') ||
          current.isBefore(dateRange[1].subtract(maxRange, 'day'), 'day')
        );
      }

      return false;
    },
    [dateRange, maxRange]
  );

  const setDateRange: RangePickerProps['onChange'] = useCallback(
    (dates: RangeValue, dateStrings: [string, string]) => {
      if (!dates || !dates[0] || !dates[1]) {
        return;
      }

      const [start, end] = dates;
      
      // 验证日期范围
      if (end.diff(start, 'day') > maxRange) {
        message.error(`日期范围不能超过 ${maxRange} 天`);
        return;
      }

      if (start.isAfter(dayjs()) || end.isAfter(dayjs())) {
        message.error('不能选择未来日期');
        return;
      }

      setDateRangeState([start, end]);
    },
    [maxRange]
  );

  const ranges: Record<string, [Dayjs, Dayjs]> = {
    '最近7天': [dayjs().subtract(6, 'day'), dayjs()],
    '最近30天': [dayjs().subtract(29, 'day'), dayjs()],
    '本月': [dayjs().startOf('month'), dayjs()],
  };

  return {
    dateRange,
    setDateRange,
    disabledDate,
    ranges,
  };
}; 